import functools
import time
from lib.log import logger


# def flow():
#     """
#     将函数转换为Flow类
#     """
#     def decorator(func):
#         @functools.wraps(func)
#         def wrapper(*args, **kw):
#             print('%s %s():' % (cls_name, func.__name__))
#             r = FunctionRule(cls_name, rule_no, is_async, func)
#             return r

#         return wrapper

#     return decorator


def retry(num_times=3, sleep_time=1, reset_func=None):
    """
    自动重试
    """
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                try:
                    value = func(*args, **kwargs)
                    # 执行成功就跳出循环，失败则重试
                    return value
                except Exception as e:
                    logger.error("执行失败", exc_info=True)
                    if reset_func is not None:
                        # 如果定义了重试前需要做的重置函数，则调用该函数
                        reset_func()
                time.sleep(sleep_time)
        return wrapper

    return decorator
